package com.huiminpay.merchant.service.impl;


import com.alibaba.fastjson.JSON;
import com.huiminpay.merchant.service.ISmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
public class ISmsServiceImpl implements ISmsService {

    @Autowired
    RestTemplate restTemplate;

    @Value("${sms.url}")
    private String smsUrl;

    @Value("${sms.effectiveTime}")
    private String smsEffectiveTime;

    @Override
    public String sendSms(String mobile) {
        String url = smsUrl+"/generate?name=sms&effectiveTime="+smsEffectiveTime;

        Map<String, Object> map = new HashMap<>();
        map.put("mobile",mobile);

        HttpEntity<Map> httpEntity = new HttpEntity<>(map);

        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);

        return JSON.parseObject(exchange.getBody())
                .getJSONObject("result").getString("key");

    }

    @Override
    public Boolean checkVerifyCode(String verifyCode, String verifyKey) {

        String url = smsUrl+"/verify?name=sms&verificationCode="+verifyCode+"&verificationKey="+verifyKey;

        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, null, String.class);

        return JSON.parseObject(exchange.getBody()).getBoolean("result");

    }
}
